package com.mytool.service.impl;

import com.mytool.model.TableMetaData;
import com.mytool.util.NamingUtil;
import com.mytool.util.TypeMappingUtil;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * DDL解析器，负责解析SQL中的表结构
 */
@Component
public class DDLParser {

    /**
     * 解析包含多个表定义的DDL
     * 
     * @param ddlSql DDL SQL语句
     * @return 表元数据列表
     */
    public List<TableMetaData> parseMultiTableDDL(String ddlSql) {
        List<TableMetaData> tableMetaDataList = new ArrayList<>();
        
        // 提取所有CREATE TABLE语句
        Pattern createTablePattern = Pattern.compile(
            "CREATE\\s+TABLE\\s+[`'\"]?(\\w+)[`'\"]?\\s*\\(([\\s\\S]*?)\\)\\s*(?:ENGINE=[\\w\\d]+)?(?:\\s*DEFAULT\\s*CHARSET=[\\w\\d]+)?(?:\\s*COMMENT\\s*=\\s*['\"]([^'\"]*)['\"])?;?",
            Pattern.CASE_INSENSITIVE
        );
        
        Matcher matcher = createTablePattern.matcher(ddlSql);
        
        while (matcher.find()) {
            String tableName = matcher.group(1);
            String columnsDefinition = matcher.group(2);
            String tableComment = matcher.group(3);
            
            TableMetaData tableMetaData = new TableMetaData();
            tableMetaData.setTableName(tableName);
            tableMetaData.setDomainObjectName(NamingUtil.tableToDomainObjectName(tableName));
            tableMetaData.setTableComment(tableComment != null ? tableComment : "");
            
            // 解析列定义
            List<Map<String, String>> fields = parseColumns(columnsDefinition);
            tableMetaData.setFields(fields);
            
            // 检查是否包含日期和小数字段
            boolean hasDateFields = false;
            boolean hasDecimalFields = false;
            boolean hasStatusField = false;
            
            for (Map<String, String> field : fields) {
                String javaType = field.get("javaType");
                String fieldName = field.get("name");
                
                if ("Date".equals(javaType) || "LocalDateTime".equals(javaType) || "LocalDate".equals(javaType)) {
                    hasDateFields = true;
                } else if ("BigDecimal".equals(javaType)) {
                    hasDecimalFields = true;
                }
                
                if ("status".equals(fieldName)) {
                    hasStatusField = true;
                }
            }
            
            tableMetaData.setHasDateFields(hasDateFields);
            tableMetaData.setHasDecimalFields(hasDecimalFields);
            tableMetaData.setHasStatusField(hasStatusField);
            
            tableMetaDataList.add(tableMetaData);
        }
        
        return tableMetaDataList;
    }
    
    /**
     * 解析列定义
     * 
     * @param columnsDefinition 列定义部分的SQL
     * @return 解析后的列信息列表
     */
    private List<Map<String, String>> parseColumns(String columnsDefinition) {
        List<Map<String, String>> columns = new ArrayList<>();
        
        // 匹配列定义
        Pattern columnPattern = Pattern.compile("`(\\w+)`\\s+(\\w+(?:\\(\\d+(?:,\\d+)?\\))?)\\s*(NOT\\s+NULL)?\\s*(DEFAULT\\s+[^,]+)?\\s*(?:COMMENT\\s*=?\\s*['\"]([^'\"]*)['\"])?[,]?", Pattern.CASE_INSENSITIVE);
        Matcher columnMatcher = columnPattern.matcher(columnsDefinition);
        
        while (columnMatcher.find()) {
            String columnName = columnMatcher.group(1);
            String columnType = columnMatcher.group(2);
            String notNull = columnMatcher.group(3);
            String defaultValue = columnMatcher.group(4);
            String comment = columnMatcher.group(5);
            
            Map<String, String> columnInfo = new HashMap<>();
            columnInfo.put("name", TypeMappingUtil.convertToCamelCase(columnName));
            columnInfo.put("columnName", columnName);
            columnInfo.put("type", columnType);
            columnInfo.put("javaType", TypeMappingUtil.convertToJavaType(columnType));
            columnInfo.put("required", notNull != null ? "true" : "false");
            columnInfo.put("defaultValue", defaultValue != null ? defaultValue.replace("DEFAULT ", "") : "");
            columnInfo.put("comment", comment != null ? comment : columnName);
            
            columns.add(columnInfo);
        }
        
        return columns;
    }
} 